package com.dailyblue.java.boot.mybatisplus.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.java.boot.mybatisplus.bean.School;
import com.dailyblue.java.boot.mybatisplus.mapper.SchoolMapper;
import com.dailyblue.java.boot.mybatisplus.service.SchoolService;
import com.dailyblue.java.spring.boot.commons.bean.JsonResult;
import com.dailyblue.java.spring.boot.commons.bean.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School> implements SchoolService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public JsonResult findAll() {
        log.info("开始获取所有学校数据.....");
        ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
        // 判断redis中是否存在所有学校数据
        String result = value.get("SCHOOL:ALL");
        log.info("redis中的内容是：{}", result);
        if (result == null) {
            // redis中不存在数据，需要从数据库中获取并存放进去
            JsonResult json = ResultTool.success(super.list());
            value.set("SCHOOL:ALL", JSONArray.toJSONString(json));
            log.info("Redis中不存在数据，从数据库中获取:{}", json);
            return json;
        }
        log.info("Redis中有数据...");
        // 如果存在
        return JSONArray.parseObject(result, JsonResult.class);
    }

}
